import { ReactElement, useState, useContext } from 'react'
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons'
import { Context } from './context'
import style from './index.module.less'

export interface TreeData {
  title: string
  key: string | number
  children?: TreeData[]
  [k: string]: any
}

interface LeafProps {
  data: TreeData
  onClick: (v: TreeData) => void
  renderNode?: (d: TreeData) => ReactElement
}

function Leaf ({ data, onClick, renderNode }: LeafProps): ReactElement {
  const { allVisible } = useContext(Context)
  const [visible, setVisible] = useState(allVisible)
  const hasChildren = data.children instanceof Array && data.children.length > 0
  return (
    <div className={style.leaf}>
      <div className={style['leaf-node']}>
        <span className={style['leaf-node-icon']} onClick={() => setVisible(!visible)}>
          {hasChildren && (
            visible ? <CaretUpOutlined /> : <CaretDownOutlined />
          )}
        </span>
        {
          typeof renderNode === 'function'
            ? (
                renderNode(data)
              )
            : <span className={style['leaf-node-name']} onClick={() => onClick(data)}>{data.title}</span>
        }

      </div>
      {
        hasChildren && visible && (
          <div className={style['leaf-list']}>
            {data.children?.map((li, i) => {
              return <Leaf key={i} data={li} onClick={onClick} renderNode={renderNode}/>
            })}
          </div>
        )
      }
    </div>
  )
}

interface Props {
  treeData: TreeData[]
  onClick?: (k: TreeData) => void
  defaultExpandAll?: boolean
  renderNode?: (d: TreeData) => ReactElement
}

function Main ({ treeData, defaultExpandAll = false, onClick = () => {}, renderNode }: Props): ReactElement {
  return (
    <Context.Provider value={{ allVisible: defaultExpandAll }}>
      <div className={style.container}>
        {treeData.map((li, i) => <Leaf key={i} data={li} onClick={onClick} renderNode={renderNode} />)}
      </div>
    </Context.Provider>
  )
}

export default Main
